﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HdipCricketClub.Models;
using HdipCricketClub.ViewModels;


namespace HdipCricketClub.Controllers
{ 
    public class SelectTeamController : Controller
    {
        private CricketClubEntities db = new CricketClubEntities();

        FixtureRepository fixtureRepository = new FixtureRepository();

        MemberRepository memberRepository = new MemberRepository();
        
        //
        //  GET: /SelectTeam/SelectFixture/

        public ViewResult SelectFixture()
        {
            var fixtures = fixtureRepository.FindFixturesWithNoTeamSelected();

            if (fixtures.Count() == 0)
            {
                ViewBag.Message = "There are no fixtures where a team has not been selected";
            }


            return View(fixtures.ToList());
        }

        //
        // GET : /SelectTeam/CreateTeam/ 
        
        public ActionResult CreateTeam(int id)
        {
            if (ModelState.IsValid)
            {
                var allFixtureTeams = db.ClubFixturePlayers.Where(cft => cft.fixture_id == id).ToList();
                var currentFixture = fixtureRepository.GetFixture(id);
                
                //
                // If a team for the fixture does not exist create it

                if (allFixtureTeams.Count == 0)
                {
                    for (int i = 1; i <= currentFixture.no_of_players; i++)
                    {
                        ClubFixturePlayer thisFixturePlayer = new ClubFixturePlayer() { fixture_id = currentFixture.fixture_id, player_no = i };
                        db.ClubFixturePlayers.AddObject(thisFixturePlayer);
                        db.SaveChanges();
                    }

                    ClubFixturePlayer clubfixtureplayer = db.ClubFixturePlayers.First(c => c.fixture_id == id);

                    int fixture_id = clubfixtureplayer.fixture_id;

                    return RedirectToAction("SelectPlayers", new { id = fixture_id }); 
                }

                //
                // else redirect to error page

                else
                {
                    return RedirectToAction("CreateError");
                }
            }
            else
            {
                return RedirectToAction("Captains", "Index");
            }
        }

        //
        // GET:  /SelectTeam/SelectPlayers/

        public ActionResult SelectPlayers(int id)
        {
            var clubfixtureplayers = db.ClubFixturePlayers.Include("Fixture").Include("Member").Include("DismissalType")
                                                      .Where(cft => cft.fixture_id == id);
            var players = memberRepository.FindAllPlayers();
            ViewBag.player_Id = new SelectList(players, "member_id", "FirstAndLastName");
            
            var currentfixture = fixtureRepository.GetFixture(id);

            ViewBag.team = currentfixture.Team.name;
            ViewBag.opponentClub = currentfixture.Opponent.club_name;
            ViewBag.opponentTeam = currentfixture.Opponent.team_name;
            ViewBag.date = currentfixture.date;
            ViewBag.Venue = currentfixture.home;
            
            return View(clubfixtureplayers.ToList());
        }

        //
        //  POST /SelectTeam/SelectPlayers/

        [HttpPost]
        public ActionResult SelectPlayers(FormCollection players)
        {
            if (ModelState.IsValid)
            {
                //
                //  save details from form collection into arrays 

                string[] formCollectionFixtureId = players.GetValues("item.fixture_id");        // fixture id
                string[] formCollectionPlayerNo = players.GetValues("item.player_no");          // player no
                string[] formCollectionPlayerId = players.GetValues("player_id");               // player id

                int fixtureId = Int32.Parse(formCollectionFixtureId[0]);

                List<ClubFixturePlayer> Validplayers = new List<ClubFixturePlayer>();

                for (int i = 0; i < formCollectionPlayerNo.Length; i++)
                {                    
                    if(formCollectionPlayerId[i] != "")
                    {
                        int validPlayerNo = Int32.Parse(formCollectionPlayerNo[i]);
                        int validPlayerId = Int32.Parse(formCollectionPlayerId[i]);
                        ClubFixturePlayer validPlayer = new ClubFixturePlayer() { fixture_id = fixtureId, player_no = validPlayerNo, player_id = validPlayerId };
                        Validplayers.Add(validPlayer);
                    }
                }

                if (Validplayers.Count != formCollectionPlayerNo.Length)
                {
                    @ViewBag.ErrorMessage = "You must enter " + formCollectionPlayerNo.Length + " players";
                    return View("ReinputSelectPlayers", Validplayers.ToList());
                }

                    //
                    //  iterate through the arrays to create players

                    for (int i = 0; i < formCollectionPlayerNo.Length; i++)
                    {
                        //
                        //  Get player from database

                        ClubFixturePlayer tempPlayer = new ClubFixturePlayer();
                        tempPlayer.fixture_id = Int32.Parse(formCollectionFixtureId[i]);
                        tempPlayer.player_no = Int32.Parse(formCollectionPlayerNo[i]);

                        ClubFixturePlayer currentPlayer = db.ClubFixturePlayers.First(cfp => cfp.fixture_id == tempPlayer.fixture_id && cfp.player_no == tempPlayer.player_no);

                        //
                        //  update player id

                        currentPlayer.player_id = Int32.Parse(formCollectionPlayerId[i]);
                        db.ObjectStateManager.ChangeObjectState(currentPlayer, EntityState.Modified);
                        db.SaveChanges();
                    }

                int thisFixture = Int32.Parse(formCollectionFixtureId[0]);

                return RedirectToAction("ConfirmTeam", new { id = thisFixture});
            }
            else
            {
                return View("CreateError");
            }
        }

        //
        //  GET: /SelectTeam/SelectPlayers


        public ActionResult ReinputSelectPlayers(List<ClubFixturePlayer> validPlayers)
        {
            var players = memberRepository.FindAllMembers();
            ViewBag.player_id = new SelectList(players, "member_id", "first_name");
            return View(validPlayers);
        }





        //
        //  Get  SelectTeam/ConfirmTeam/
        
        public ActionResult ConfirmTeam(int id)
        {
            var clubFixturePlayers = db.ClubFixturePlayers.Where(cfp => cfp.fixture_id == id);

            return View(clubFixturePlayers.ToList());
        }

        //
        //  POST SelectTeam/ConfirmTeam/

        [HttpPost]
        public ActionResult ConfirmTeam(FormCollection players)
        {
            if (ModelState.IsValid)
            {
                string[] formCollectionFixtureId = players.GetValues("item.fixture_id");
                string[] formCollectionPlayerNo = players.GetValues("item.player_no");
                string[] formCollectionPlayerId = players.GetValues("item.player_id");
                string[] formCollectionContact = players.GetValues("item.contact");
                string[] formCollectionConfirmed = players.GetValues("item.confirmed");

                for(int i = 0; i < formCollectionPlayerNo.Length; i++)
                {
                    ClubFixturePlayer tempPlayer = new ClubFixturePlayer();
                    tempPlayer.fixture_id = Int32.Parse(formCollectionFixtureId[i]);
                    tempPlayer.player_no = Int32.Parse(formCollectionPlayerNo[i]);

                    ClubFixturePlayer currentPlayer = db.ClubFixturePlayers.First(cp => cp.fixture_id == tempPlayer.fixture_id && cp.player_no == tempPlayer.player_no);

                    currentPlayer.player_id = Int32.Parse(formCollectionPlayerId[i]);

                    if (formCollectionContact[i] == "true")
                    {
                        currentPlayer.contact = false;
                        currentPlayer.contacted = true;
                    }
                    else
                    {
                        currentPlayer.contact = false;
                        currentPlayer.contacted = false;
                    }

                    if (formCollectionConfirmed[i] == "true")
                    {
                        currentPlayer.confirmed = true;
                    }

                    else if (formCollectionConfirmed[i] == "false")
                    {
                        currentPlayer.confirmed = false;
                    }
                    else
                    {
                        currentPlayer.confirmed = null;
                    }
                    db.ObjectStateManager.ChangeObjectState(currentPlayer, EntityState.Modified);
                    db.SaveChanges();
                }

                int thisFixture = Int32.Parse(formCollectionFixtureId[0]);

                return RedirectToAction("ConfirmedTeam", new { id = thisFixture });
            }
            return View();
        }

        //
        //  GET /SelectTeam/ConfirmedTeam/

        public ActionResult ConfirmedTeam(int id)
        {
            var clubFixturePlayers = db.ClubFixturePlayers.Where(cfp => cfp.fixture_id == id).OrderBy(cfp => cfp.confirmed).ThenBy(cfp => cfp.player_no);

            return View(clubFixturePlayers.ToList());
        }
        

        public ActionResult Confirmed()
        {
            ViewBag.Message = "This is the /SelectTeam/Confirmed Action";
            return View();
        }
                
        //
        //  GET /SelectTeam/CreateError/

        public ActionResult CreateError()
        {

            return View();
        }
                    
        //         
        // GET: /SelectTeam/Details/5

        public ViewResult Details(int id)
        {
            Fixture fixture = db.Fixtures.Single(f => f.fixture_id == id);
            return View(fixture);
        }

        //
        // GET: /SelectTeam/Create

        public ActionResult Create()
        {
            ViewBag.team_id = new SelectList(db.Teams, "team_id", "name");
            ViewBag.opponent_id = new SelectList(db.Opponents, "opponent_id", "club_name");
            return View();
        } 

        //
        // POST: /SelectTeam/Create

        [HttpPost]
        public ActionResult Create(Fixture fixture)
        {
            if (ModelState.IsValid)
            {
                db.Fixtures.AddObject(fixture);
                db.SaveChanges();
                return RedirectToAction("Index");  
            }

            ViewBag.team_id = new SelectList(db.Teams, "team_id", "name", fixture.team_id);
            ViewBag.opponent_id = new SelectList(db.Opponents, "opponent_id", "club_name", fixture.opponent_id);
            return View(fixture);
        }
        
        //
        // GET: /SelectTeam/Edit/5
 
        public ActionResult Edit(int id)
        {
            Fixture fixture = db.Fixtures.Single(f => f.fixture_id == id);
            ViewBag.team_id = new SelectList(db.Teams, "team_id", "name", fixture.team_id);
            ViewBag.opponent_id = new SelectList(db.Opponents, "opponent_id", "club_name", fixture.opponent_id);
            return View(fixture);
        }

        //
        // POST: /SelectTeam/Edit/5

        [HttpPost]
        public ActionResult Edit(Fixture fixture)
        {
            if (ModelState.IsValid)
            {
                db.Fixtures.Attach(fixture);
                db.ObjectStateManager.ChangeObjectState(fixture, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.team_id = new SelectList(db.Teams, "team_id", "name", fixture.team_id);
            ViewBag.opponent_id = new SelectList(db.Opponents, "opponent_id", "club_name", fixture.opponent_id);
            return View(fixture);
        }

        //
        // GET: /SelectTeam/Delete/5
 
        public ActionResult Delete(int id)
        {
            Fixture fixture = db.Fixtures.Single(f => f.fixture_id == id);
            return View(fixture);
        }

        //
        // POST: /SelectTeam/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {            
            Fixture fixture = db.Fixtures.Single(f => f.fixture_id == id);
            db.Fixtures.DeleteObject(fixture);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

       





    }
}